package cn.cosmosx.img;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageWatermark {

    public static void main(String[] args) throws IOException {
        String imgPath = "C:\\Users\\geng\\Desktop\\流水.png";
        BufferedImage bufferedImage = readImgRaw(imgPath);
        BufferedImage newImage = drawWatermark(bufferedImage, "仅供流水查询使用");
        writeImg(newImage, "C:\\Users\\geng\\Desktop\\流水_水印.png");
    }

    static BufferedImage readImgRaw(String imgPath) throws IOException {
        return ImageIO.read(new File(imgPath));
    }

    static BufferedImage drawWatermark(BufferedImage image, String watermark) {
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        // 创建画笔，添加水印
        Graphics2D d = bufferedImage.createGraphics();
        // 获取到的原始图片的图片对象
        d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
        d.setColor(new Color(120, 120, 120, 120));
        d.setFont(new Font("微软雅黑", Font.ITALIC, 60));
        int x = getWatermarkLength(watermark, d) / 2;
        int y = image.getHeight() / 2;
        d.drawString(watermark, x, y);
        d.dispose();
        return bufferedImage;
    }

    static void writeImg(BufferedImage img, String imgPath) throws IOException {
        ImageIO.write(img, "png", new FileOutputStream(imgPath));
    }

    /**
     * 获取水印文字的长度
     *
     * @param waterMarkContent
     * @param g
     * @return
     */
    static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

}
